﻿using System;
using System.Text;
using TI_BLE_HCI_ClientLib.GenericHCIEntities;
using TI_BLE_HCI_ClientLib.HCIBaseEntities;

namespace TI_BLE_HCI_ClientLib.HCIEvents
{
    public class HCIEvent_ATT_Prepare_Write_Characteristic_Value_Request : HCIEvent_GATT_Base_Event
    {
        public ushort AttributeHandle
        {
            get
            {
                if (base.PduLen < 2) throw new ArgumentException("PduLen<2");

                return (ushort)(base.Pdu[0] + (base.Pdu[1] << 8));
            }
        }

        public ushort Offset
        {
            get
            {
                if (base.PduLen < 4) throw new ArgumentException("PduLen<4");

                return (ushort)(base.Pdu[2] + (base.Pdu[3] << 8));
            }
        }

        byte[] valueByteArray
        {
            get
            {
                var valueArray = new byte[base.PduLen - 4];

                Array.Copy(base.Pdu,4,valueArray,0,valueArray.Length);

                return valueArray;
            }
        }

        public byte[] Value
        {
            get
            {
                return valueByteArray;
            }
        }

        public string ValueAsString
        {
            get
            {
                try
                {
                    return new string(Encoding.UTF8.GetChars(valueByteArray));
                }
                catch
                {
                    return null;
                }
            }
        }

        public bool ValueAsBoolean
        {
            get
            {
                if (base.PduLen < 5) throw new ArgumentException("PduLen<5");

                return valueByteArray[0] != 0;
            }
        }

        public byte ValueAsUInt8
        {
            get
            {
                if (base.PduLen < 5) throw new ArgumentException("PduLen<5");

                return valueByteArray[0];
            }
        }

        public ushort ValueAsUInt16
        {
            get
            {
                if (base.PduLen < 5) throw new ArgumentException("PduLen<6");

                return (ushort)(valueByteArray[0] + (valueByteArray[1] << 8));
            }
        }

        public HCIEvent_ATT_Prepare_Write_Characteristic_Value_Request(HCIVendorSpecificEventHostErrorCode status,
            ushort connHandle, byte pduLen, byte[] pdu) : base(status, connHandle, pduLen, pdu)
        {
        }
    }
}
